#!/bin/bash

CUR_PATH=$(dirname $(readlink -f "$0"))
HEAD_SH="${CUR_PATH}/makeself-header.sh"
MAKESELF_PATH=$1
DST_PATH=$2
PACK_NAME=$3
HELP_INFO="${DST_PATH}/driver/script/help.info"
#PACK_COMPONENT="ASCEND310P DRIVER RUN PACKAGE"
INSTALL_SH="driver/script/install.sh"
REBUILD_FLAG="${DST_PATH}/driver/script/run_driver_install.sh"
REBUILD_SH="run_driver_ko_rebuild.sh"
INSTALL_LOG="/var/log/ascend_seclog/"

show_help_and_exit()
{
        echo "Usage:"
        printf "%-80s\n" "	$0 <makeself script> <source path> <output package name>"
        printf "%-80s %-30s\n" "	$0 ./makeself-2.4.0/makeself.sh tmp/ Ascendxxx-driver-xxx.run" "## Add header for img"
        exit 1
}

check_para()
{
	if [ ! -e "${HEAD_SH}" ];then
		echo "[ERROR]header script: ${HEAD_SH} no exist, please check."
		show_help_and_exit
	fi
	chmod +x ${HEAD_SH}
	if [ ! -e "${MAKESELF_PATH}" ];then
		echo "[ERROR]makeself script: ${MAKESELF_PATH} no exist, please check."
		show_help_and_exit
        fi
	chmod +x ${MAKESELF_PATH}
	if [ ! -d "${DST_PATH}" ];then
		echo "[ERROR]source path: ${DST_PATH} no exist, please check."
		show_help_and_exit
	fi
	if [[ ${PACK_NAME} =~ .run$ ]];then
		echo "[INFO]package name: ${PACK_NAME}"
		return 0
	fi
	echo "[ERROR]package name: ${PACK_NAME}. The package must be in the .run format."
	show_help_and_exit
}

change_scene()
{
	if [ ! -e ${REBUILD_FLAG} ];then
		echo "[INFO] ${REBUILD_FLAG} no exist no need remove rebuild flag"
		return 1
	fi
	sed -i 's/do_rebuild_ko=y//g' ${REBUILD_FLAG}
}

rebuild_ko()
{
	if [ ! -e ${REBUILD_SH} ];then
		echo "[ERROR]rebuild scripts, please check package is support rebuild."
		exit 1
	fi
	if [ ! -d ${INSTALL_LOG} ];then
		mkdir -p ${INSTALL_LOG}
	fi
	cp -f ${REBUILD_SH} ${DST_PATH}/driver/script/
	bash ${DST_PATH}/driver/script/${REBUILD_SH} --force
	if [ $? -ne 0 ];then
		echo "[ERROR]rebuild failed."
		exit 1
	fi
}
#check para
if [ $# -lt 3 ];then
        show_help_and_exit
fi

#start repack
check_para
change_scene
rebuild_ko

${MAKESELF_PATH} --header ${HEAD_SH} --help-header ${HELP_INFO} --pigz --complevel 4 --nomd5 --sha256 \
	${DST_PATH} ${PACK_NAME} "ASCEND DRIVER RUN PACKAGE" ${INSTALL_SH}
if [ $? -ne 0 ];then
	echo "[ERROR]repack failed."
	exit 1
fi
echo "[INFO]repack success."

